# -*- coding: utf-8 -*-

import os

from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Gio

class ToquinUSBCopier(Gtk.Dialog):
	toquin_model = None
	progress_bar = None
	
	def __init__(self, toquin_model, title=None, parent=None, flags=0, buttons=None):
		Gtk.Dialog.__init__(self, title, parent, flags, buttons)
		self.toquin_model = toquin_model

		information_label = Gtk.Label()
		information_label.set_text("Progreso:")
		self.get_content_area().pack_start(information_label)
		
		self.progress_bar = Gtk.ProgressBar()
		self.get_content_area().pack_start(self.progress_bar)

		self.get_content_area().show_all()
		self.set_modal(True)

	def copy_installables(self):
		mountable_device = Gio.VolumeMonitor()
		max_partition_size = 0
		max_mount = None
		
		for mount in mountable_device.get_mounts():
			drive = mount.get_drive()	

			if drive.is_media_removable():
				try:
					filesystem_info = mount.get_root().query_filesystem_info('filesystem::free')
					if filesystem_info:
						partition_size = filesystem_info.get_attribute_uint64('filesystem::free')
						
						if (partition_size > max_partition_size):
							max_partition_size = partition_size
							max_mount = mount
				except Exception:
					print "Error querying %s" % drive

		if not max_mount:
			print "No mount found"
			return

		print "Writing to %s" % max_mount.get_root().get_path()

		GObject.idle_add(self.copy_installables_async, max_mount, self.toquin_model.getMarkedForInstallation())

		self.run()

	def copy_installables_async(self, mount_point, installables):
		copy_path = os.path.join(mount_point.get_root().get_path(), "Toquin")
		copy_directory = Gio.File(copy_path)

		# Pre-checks
		if copy_directory.query_exists():
			if copy_directory.query_file_type(Gio.FILE_QUERY_INFO_NONE) != Gio.FILE_TYPE_DIRECTORY:
				raise Exception()
		else:
			copy_directory.make_directory()

		# Config
		file_root = ""

		for i in range(0, len(installables)):
			item_path = os.path.join(file_root, installables[i].filename)
			item_file = Gio.File(item_path)
			target_path = os.path.join(copy_path, os.path.basename(installables[i].filename))
			target = Gio.File(target_path)
			
			item_file.copy(target, self.report_copy_progress, Gio.FILE_COPY_OVERWRITE, None, [i, len(installables)])

		self.response(0)
		
	def report_copy_progress(self, current_bytes, total_bytes, file_numbers):
		self.progress_bar.set_fraction(float(file_numbers[0])/file_numbers[1] + (float(current_bytes)/total_bytes)/(file_numbers[1]))
